/**
 * Created by Dalyn on 2017/2/28.
 * 测试文件
 */
import React from "react";
import GetQiNiuToken from "./mutation/GetQiNiuToken"
import Relay from "react-relay";

/*导出组件*/
export default class Product extends React.Component{
    constructor(props){
        super(props)
        this.state={}
        this.token=''
    }

    upload(){
        let myfile = document.getElementById('choiceFile').files[0];
        let name = myfile.name
        Relay.Store.commitUpdate(
            new GetQiNiuToken({}), {
                onSuccess: (res) => {
                    console.warn(res);
                    let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                    if(errorCode==0){
                        let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken
                        this.token = qiniutoken;
                        this.upLoadFile(myfile,qiniutoken,name)
                    }
                }
            }
        )
    }


    upLoadFile(file, token,name) {
        let upLoadUrl = "http://up-z2.qiniu.com";
        let xhr = new XMLHttpRequest();
        xhr.open("POST", upLoadUrl, true);

        let formData = new FormData();
        formData.append('file', file);
        formData.append('token', token);
        formData.append('key',name);

        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                  console.dir(JSON.parse(xhr.responseText));
                } else {
                    alert('111')
                }
            }
        };
        xhr.send(formData);
    }



    render(){
        return (
            <div className="right">
                <p onClick={this.upload.bind(this)}>666666666666</p>
                <input type="file"  id="choiceFile"  ref={'aa'}/>
            </div>
        )
    }
}